/**
 * Copyright (c) 2020-2024, huli.com
 * All rights reserved.
 */
package com.xiaohujr.xuexue.leetcode.interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 三个线程交替顺序打印ABC.
 *
 * @author Xue Xue (xuexue1@huli.com)
 * @version 1.0
 * @since 2021/1/8
 */
public class printThreeThreadA {
    static int a = 0;

    public static void main(String[] args) throws InterruptedException {
        Lock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        Condition condition3 = lock.newCondition();

        new Thread(()->{
            while (a<=100){
                lock.lock();
                System.out.println(Thread.currentThread().getName()+":"+a++);
                condition2.signal();
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }).start();
        new Thread(() -> {
            while (a<=100){
                lock.lock();
                System.out.println(Thread.currentThread().getName()+":"+a++);

                try {
                    condition1.await();

                    condition2.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }, "thread 1").start();

        new Thread(()->{
            while (a<=100){
                lock.lock();
                System.out.println(Thread.currentThread().getName()+":"+a++);
                condition3.signal();
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    lock.unlock();
                }
            }
        },"thread 2").start();

        new Thread(()->{
            while (a<=100){
                lock.lock();
                System.out.println(Thread.currentThread().getName()+":"+a++);
                condition1.signal();
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    lock.unlock();
                }
            }
        },"thread 3").start();
    }
}
